const { USER_REGISTER, USER_LOGIN, USER_INFO } = require('./consts')
const { SuccessModel, ErrorModel } = require('../model/result')
const { handleUserRegister, handleUserLogin } = require('../controller/user')
const { authFail } = require('../config/error/user')
const express = require('express')
const router = express.Router()

// 处理用户相关路由
router.get(USER_INFO, (req, res, next) => {
  console.log('req.session,', req.session)
  // 无权限
  if (!req.session) {
    return res.json(new ErrorModel(authFail))
  }
  return res.json(new SuccessModel({
    message: '用户信息获取',
    data: {
      username: 'chigga',
      age: 18
    }
  }))
})
router.post(USER_REGISTER, async (req, res, next) => {
  // 用户注册
  const result = await handleUserRegister(req.body)
  return res.json(result)
})
router.post(USER_LOGIN, async (req, res, next) => {
// 用户登录
  const result = await handleUserLogin(req.body)
  // 保存登录状态
  if (result.code === 200) {
    const { username, password, gender } = result.data
    req.session.username = username
    req.session.password = password
    req.session.gender = gender
    // 同步到Redis中
    // await setRedis(req.userId, req.session)
  }
  return res.json(result)
})

module.exports = router
